package com.yimo.chromedriver;

import com.yimo.common.util.HttpClient;
import lombok.Data;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * create by jsm on 2018/11/7
 */
@Component
@Data
public class Nineteen extends Crawler {
    @Value("${chromedriver.savePath:/Users/yimouser/Documents}")
    private String savePath;
    private ChromeDriver chromeDriver;
    @Resource
    private HttpClient httpClient;
    Calendar calendar = Calendar.getInstance();

    public ChromeDriver climb() throws IOException {
        Date now = new Date();
        calendar.setTime(now);
        String subFolder = savePath + "/nineteen/" + calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + now.getTime();
        File subFolderFile = new File(subFolder);
        if (subFolderFile.exists() == false) {
            subFolderFile.mkdirs();
        }
        if (chromeDriver == null) {
            chromeDriver = open();
        } else {
            chromeDriver.get(getUrl());
        }
        StringBuffer stringBuffer = new StringBuffer();
        List <WebElement> contents = chromeDriver.findElements(By.className("view-data"));
        for (WebElement content : contents) {
            stringBuffer.append(content.getText());
            List <WebElement> imgs = content.findElements(By.tagName("img"));
            for (WebElement img : imgs) {
                String src = img.getAttribute("src");
                InputStream inputStream = httpClient.doGetStream(src);
                BufferedImage buffer = ImageIO.read(inputStream);
                ImageIO.write(buffer, "png", new File(subFolder + "/i" + new Date().getTime() + ".png"));
            }
        }
        File contentFile = new File(subFolder + "/c" + new Date().getTime() + ".txt");
        FileOutputStream fw = new FileOutputStream(contentFile);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fw, "UTF-8"));
        bw.write(stringBuffer.toString());
        bw.flush();
        bw.close();
        return chromeDriver;
    }
}
